<template>
  <el-dialog
    v-model="visible"
    title="批量邀请成员"
    width="600px"
    :before-close="handleClose"
  >
    <div class="batch-invite-content">
      <!-- 邀请方式选择 -->
      <div class="invite-method">
        <h4 class="section-title">邀请方式</h4>
        <el-radio-group v-model="inviteMethod" @change="handleMethodChange">
          <el-radio value="email">邮箱邀请</el-radio>
          <el-radio value="username">用户名邀请</el-radio>
          <el-radio value="file">文件导入</el-radio>
        </el-radio-group>
      </div>

      <!-- 邮箱邀请 -->
      <div v-if="inviteMethod === 'email'" class="invite-section">
        <h4 class="section-title">邮箱列表</h4>
        <el-input
          v-model="emailInput"
          type="textarea"
          :rows="6"
          placeholder="请输入邮箱地址，每行一个&#10;例如：&#10;user1@example.com&#10;user2@example.com&#10;user3@example.com"
          @input="parseEmails"
        />
        <div class="input-hint">
          <el-icon><InfoFilled /></el-icon>
          <span>每行输入一个邮箱地址，系统将自动发送邀请邮件</span>
        </div>
      </div>

      <!-- 用户名邀请 -->
      <div v-if="inviteMethod === 'username'" class="invite-section">
        <h4 class="section-title">用户名列表</h4>
        <el-input
          v-model="usernameInput"
          type="textarea"
          :rows="6"
          placeholder="请输入用户名，每行一个&#10;例如：&#10;user1&#10;user2&#10;user3"
          @input="parseUsernames"
        />
        <div class="input-hint">
          <el-icon><InfoFilled /></el-icon>
          <span>每行输入一个用户名，系统将直接添加到团队</span>
        </div>
      </div>

      <!-- 文件导入 -->
      <div v-if="inviteMethod === 'file'" class="invite-section">
        <h4 class="section-title">文件导入</h4>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".csv,.txt,.xlsx"
          @change="handleFileChange"
          @remove="handleFileRemove"
        >
          <el-button :icon="Upload">选择文件</el-button>
          <template #tip>
            <div class="upload-tip">
              支持 CSV、TXT、Excel 格式，文件大小不超过 1MB
            </div>
          </template>
        </el-upload>
        <div class="file-format-hint">
          <h5>文件格式要求：</h5>
          <ul>
            <li><strong>CSV/TXT:</strong> 每行一个邮箱或用户名</li>
            <li><strong>Excel:</strong> 第一列为邮箱或用户名</li>
          </ul>
        </div>
      </div>

      <!-- 角色设置 -->
      <div class="role-setting">
        <h4 class="section-title">默认角色</h4>
        <el-radio-group v-model="defaultRole">
          <el-radio value="MEMBER">
            <div class="role-option">
              <el-icon><User /></el-icon>
              <span>普通成员</span>
            </div>
          </el-radio>
          <el-radio value="ADMIN">
            <div class="role-option">
              <el-icon><Management /></el-icon>
              <span>管理员</span>
            </div>
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 预览列表 -->
      <div v-if="inviteList.length > 0" class="preview-section">
        <h4 class="section-title">
          邀请预览 ({{ inviteList.length }} 个)
          <el-button 
            type="text" 
            size="small" 
            @click="clearInviteList"
            :icon="Delete"
          >
            清空
          </el-button>
        </h4>
        <div class="invite-preview">
          <div 
            v-for="(item, index) in inviteList" 
            :key="index"
            class="invite-item"
            :class="{ 'invalid': !item.valid }"
          >
            <div class="invite-info">
              <el-icon v-if="item.valid" class="status-icon valid"><Check /></el-icon>
              <el-icon v-else class="status-icon invalid"><Close /></el-icon>
              <span class="invite-target">{{ item.target }}</span>
              <el-tag :type="getRoleTagType(defaultRole)" size="small">
                {{ getRoleLabel(defaultRole) }}
              </el-tag>
            </div>
            <el-button 
              type="text" 
              size="small" 
              @click="removeInviteItem(index)"
              :icon="Delete"
            />
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div v-if="inviteList.length > 0" class="invite-stats">
        <el-descriptions :column="3" size="small" border>
          <el-descriptions-item label="总数">{{ inviteList.length }}</el-descriptions-item>
          <el-descriptions-item label="有效">{{ validInviteCount }}</el-descriptions-item>
          <el-descriptions-item label="无效">{{ invalidInviteCount }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="validInviteCount === 0"
          :loading="loading"
        >
          邀请 {{ validInviteCount }} 个成员
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  InfoFilled,
  Upload,
  User,
  Management,
  Check,
  Close,
  Delete
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'

interface Props {
  modelValue: boolean
  teamId: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', inviteData: {
    method: string
    targets: string[]
    role: string
  }): void
}

interface InviteItem {
  target: string
  valid: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const inviteMethod = ref<'email' | 'username' | 'file'>('email')
const defaultRole = ref<'MEMBER' | 'ADMIN'>('MEMBER')
const emailInput = ref('')
const usernameInput = ref('')
const inviteList = ref<InviteItem[]>([])
const loading = ref(false)
const uploadRef = ref()

// 计算属性
const validInviteCount = computed(() => 
  inviteList.value.filter(item => item.valid).length
)

const invalidInviteCount = computed(() => 
  inviteList.value.filter(item => !item.valid).length
)

// 邮箱验证正则
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

// 用户名验证正则（字母数字下划线，3-20位）
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/

// 解析邮箱
const parseEmails = () => {
  const emails = emailInput.value
    .split('\n')
    .map(email => email.trim())
    .filter(email => email.length > 0)
  
  inviteList.value = emails.map(email => ({
    target: email,
    valid: emailRegex.test(email)
  }))
}

// 解析用户名
const parseUsernames = () => {
  const usernames = usernameInput.value
    .split('\n')
    .map(username => username.trim())
    .filter(username => username.length > 0)
  
  inviteList.value = usernames.map(username => ({
    target: username,
    valid: usernameRegex.test(username)
  }))
}

// 处理文件变化
const handleFileChange = (file: any) => {
  const fileType = file.name.split('.').pop()?.toLowerCase()
  
  if (!['csv', 'txt', 'xlsx'].includes(fileType || '')) {
    ElMessage.error('不支持的文件格式')
    return
  }
  
  if (file.size > 1024 * 1024) {
    ElMessage.error('文件大小不能超过 1MB')
    return
  }
  
  // 读取文件内容
  const reader = new FileReader()
  reader.onload = (e) => {
    const content = e.target?.result as string
    parseFileContent(content, fileType)
  }
  reader.readAsText(file.raw)
}

// 解析文件内容
const parseFileContent = (content: string, fileType: string) => {
  let targets: string[] = []
  
  if (fileType === 'csv' || fileType === 'txt') {
    targets = content
      .split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0)
  } else if (fileType === 'xlsx') {
    // 简单处理Excel文件（实际项目中可能需要使用专门的库）
    targets = content
      .split('\n')
      .map(line => line.split(',')[0]?.trim())
      .filter(target => target && target.length > 0)
  }
  
  inviteList.value = targets.map(target => ({
    target,
    valid: emailRegex.test(target) || usernameRegex.test(target)
  }))
}

// 处理文件移除
const handleFileRemove = () => {
  inviteList.value = []
}

// 处理邀请方式变化
const handleMethodChange = () => {
  // 清空输入和列表
  emailInput.value = ''
  usernameInput.value = ''
  inviteList.value = []
  
  // 清空文件上传
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 移除邀请项
const removeInviteItem = (index: number) => {
  inviteList.value.splice(index, 1)
}

// 清空邀请列表
const clearInviteList = () => {
  inviteList.value = []
  emailInput.value = ''
  usernameInput.value = ''
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 获取角色标签类型
const getRoleTagType = (role: string) => {
  return role === 'ADMIN' ? 'warning' : 'info'
}

// 获取角色标签
const getRoleLabel = (role: string) => {
  return role === 'ADMIN' ? '管理员' : '普通成员'
}

// 处理确认
const handleConfirm = async () => {
  if (validInviteCount.value === 0) {
    ElMessage.warning('请添加有效的邀请目标')
    return
  }
  
  const validTargets = inviteList.value
    .filter(item => item.valid)
    .map(item => item.target)
  
  emit('confirm', {
    method: inviteMethod.value,
    targets: validTargets,
    role: defaultRole.value
  })
}

// 处理关闭
const handleClose = () => {
  clearInviteList()
  visible.value = false
}

// 监听对话框打开
watch(visible, (newVal) => {
  if (newVal) {
    // 重置状态
    inviteMethod.value = 'email'
    defaultRole.value = 'MEMBER'
    clearInviteList()
  }
})
</script>

<style scoped lang="scss">
.batch-invite-content {
  .section-title {
    font-size: 14px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin: 0 0 12px 0;
  }

  .invite-method {
    margin-bottom: 24px;
  }

  .invite-section {
    margin-bottom: 24px;

    .input-hint {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-top: 8px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }

    .upload-tip {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 4px;
    }

    .file-format-hint {
      margin-top: 12px;
      padding: 12px;
      background: var(--el-bg-color-page);
      border-radius: 6px;

      h5 {
        margin: 0 0 8px 0;
        font-size: 13px;
        color: var(--el-text-color-primary);
      }

      ul {
        margin: 0;
        padding-left: 16px;
        font-size: 12px;
        color: var(--el-text-color-secondary);

        li {
          margin-bottom: 4px;
        }
      }
    }
  }

  .role-setting {
    margin-bottom: 24px;

    .role-option {
      display: flex;
      align-items: center;
      gap: 6px;
    }
  }

  .preview-section {
    margin-bottom: 24px;

    .invite-preview {
      max-height: 200px;
      overflow-y: auto;
      border: 1px solid var(--el-border-color-light);
      border-radius: 6px;

      .invite-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 12px;
        border-bottom: 1px solid var(--el-border-color-lighter);

        &:last-child {
          border-bottom: none;
        }

        &.invalid {
          background: var(--el-color-danger-light-9);
        }

        .invite-info {
          display: flex;
          align-items: center;
          gap: 8px;
          flex: 1;

          .status-icon {
            font-size: 14px;

            &.valid {
              color: var(--el-color-success);
            }

            &.invalid {
              color: var(--el-color-danger);
            }
          }

          .invite-target {
            font-size: 14px;
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }

  .invite-stats {
    margin-bottom: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
